// const API_BASE_URL = 'http://localhost:3000/api'

class AuthService {
  async login(credentials) {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    const mockUsers = [
      { id: 1, email: 'admin@example.com', password: 'admin123', name: '管理员', role: 'admin', permissions: ['all'], balance: 0 },
      { id: 2, email: 'user@example.com', password: 'user123', name: '普通用户', role: 'user', permissions: ['read'], balance: 1000 }
    ]
    
    const user = mockUsers.find(u => 
      u.email === credentials.email && u.password === credentials.password
    )
    
    if (!user) {
      throw new Error('邮箱或密码错误')
    }
    
    const { password, ...userWithoutPassword } = user
    
    return {
      user: userWithoutPassword,
      token: 'mock-jwt-token-' + user.id
    }
  }

  async register(userData) {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟邮箱已存在检查
    const existingUsers = [
      { email: 'admin@example.com' },
      { email: 'user@example.com' }
    ]
    
    if (existingUsers.some(u => u.email === userData.email)) {
      throw new Error('邮箱已被注册')
    }
    
    if (userData.password !== userData.confirmPassword) {
      throw new Error('两次输入的密码不一致')
    }
    
    const newUser = {
      id: Date.now(),
      email: userData.email,
      name: userData.name,
      role: 'user',
      permissions: ['read'],
      balance: 100, // 新用户默认余额
      createdAt: new Date().toISOString()
    }
    
    return {
      user: newUser,
      token: 'mock-jwt-token-' + newUser.id
    }
  }

  async updateProfile(token, userData) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟验证token
    if (!token) {
      throw new Error('未授权访问')
    }
    
    return {
      user: {
        ...userData,
        updatedAt: new Date().toISOString()
      }
    }
  }

  async changePassword(token, passwordData) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (!token) {
      throw new Error('未授权访问')
    }
    
    if (passwordData.newPassword !== passwordData.confirmNewPassword) {
      throw new Error('两次输入的密码不一致')
    }
    
    return { message: '密码修改成功' }
  }

  async getUserProfile(token) {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    if (!token) {
      throw new Error('未授权访问')
    }
    
    // 模拟用户数据
    return {
      id: 1,
      email: 'user@example.com',
      name: '普通用户',
      role: 'user',
      permissions: ['read'],
      createdAt: '2024-01-01T00:00:00.000Z'
    }
  }
}

export const authService = new AuthService()